//
//  SEGSafaKeyboard.m
//  Customkeyboard
//
//  Created by Clavis on 2020/1/17.
//  Copyright © 2020 Clavis. All rights reserved.
//

#import "SEGSafaKeyboard.h"
#import <Commom/SEGLayoutMacro.h>
#import <AudioToolbox/AudioToolbox.h>

#define SEGSakeKeyBoardWidth [UIScreen mainScreen].bounds.size.width
#define SEGSakeKeyBoardHeight 216
//#define SEGSakeKeyBoardBannerHeight 36
//#define SEGSakeKeyBoardPadHeight 180


#define SEGSakeKeyBoardBannerHeight 0
#define SEGSakeKeyBoardPadHeight 216

@interface SEGSafaKeyboard ()

@property (nonatomic, strong) UIView *bannerView;
@property (nonatomic, strong) UIView *numberPadView;
@property (nonatomic, strong) UIView *letterPadView;
@property (nonatomic, strong) UIView *symbolPadView;
@property (nonatomic, strong) NSMutableArray *letterButtonArray;

@end

@implementation SEGSafaKeyboard {
    NSTimer *_timer;
}

- (void)dealloc {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self setupUI];
    }
    return self;
}
    

- (void)setupUI {
    self.backgroundColor = UIColor.lightGrayColor;
  
    [self setupNumberPad];
    [self setupSymbolPad];
    [self setupLetterPad];
}

- (void)setupNumberPad {
    self.numberPadView = [[UIView alloc] initWithFrame:CGRectMake(0, SEGSakeKeyBoardBannerHeight, SEGSakeKeyBoardWidth, SEGSakeKeyBoardPadHeight)];
    self.numberPadView.backgroundColor = UIColor.lightGrayColor;
    [self addSubview:self.numberPadView];
    
    CGFloat margin = 8;
    NSInteger numberOfRow = 4;
    NSInteger numberOfColumn = 3;
    CGFloat subHeight = floor((SEGSakeKeyBoardPadHeight - margin*(numberOfRow+1))*1.0/numberOfRow);
    CGFloat subWidth = floor((SEGSakeKeyBoardWidth - margin*(numberOfColumn+1))*1.0/numberOfColumn);
    
    for (int i = 0; i < 9; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(i%3*(margin+subWidth) + margin, i/3*(margin+subHeight) + margin, subWidth, subHeight);
        button.backgroundColor = UIColor.whiteColor;
        [button setTitle:[NSString stringWithFormat:@"%d", i+1] forState:UIControlStateNormal];
        [button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        button.layer.cornerRadius = 4;
        [button addTarget:self action:@selector(charaterButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        [self.numberPadView addSubview:button];
    }
    
    // 0
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(1*(margin+subWidth) + margin, 3*(margin+subHeight) + margin, subWidth, subHeight);
        button.backgroundColor = UIColor.whiteColor;
        [button setTitle:@"0" forState:UIControlStateNormal];
        [button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        button.layer.cornerRadius = 4;
        [button addTarget:self action:@selector(charaterButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        [self.numberPadView addSubview:button];
    }
    
    
    // delete
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(2*(margin+subWidth) + margin, 3*(margin+subHeight) + margin, subWidth, subHeight);
        button.backgroundColor = UIColor.whiteColor;
        [button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        button.layer.cornerRadius = 4;
        
        [button setImage:SEGAutoPicName(@"safeKeyboard_delete") forState:UIControlStateNormal];
        [button addTarget:self action:@selector(deleteButtonTap) forControlEvents:UIControlEventTouchUpInside];
        UILongPressGestureRecognizer *press = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(reduceText:)];
        [button addGestureRecognizer:press];
        
        
        [self.numberPadView addSubview:button];
    }
    
    // switch to Letter
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(margin, 3*(margin+subHeight) + margin, subWidth, subHeight);
        button.backgroundColor = UIColor.whiteColor;
        [button setTitle:@"ABC" forState:UIControlStateNormal];
        [button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        button.layer.cornerRadius = 4;
        [button addTarget:self action:@selector(switchToLetterPadButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        [self.numberPadView addSubview:button];
    }
}

- (void)setupSymbolPad {
    self.symbolPadView = [[UIView alloc] initWithFrame:CGRectMake(0, SEGSakeKeyBoardBannerHeight, SEGSakeKeyBoardWidth, SEGSakeKeyBoardPadHeight)];
    self.symbolPadView.backgroundColor = UIColor.lightGrayColor;
    [self addSubview:self.symbolPadView];
    
    CGFloat margin = 8;
    NSInteger numberOfRow = 4;
    NSInteger numberOfColumn = 10;
    CGFloat subHeight = floor((SEGSakeKeyBoardPadHeight - margin*(numberOfRow+1))*1.0/numberOfRow);
    CGFloat subWidth = floor((SEGSakeKeyBoardWidth - margin*(numberOfColumn+1))*1.0/numberOfColumn);
    
    NSString *symbolString = @"~ ` ! @ # $ % ^ & * . , _ - + = ? | \\ / ( ) [ ] { } < >";
    NSArray *sysmbolArray = [symbolString componentsSeparatedByString:@" "];
    [sysmbolArray enumerateObjectsUsingBlock:^(NSString * _Nonnull symbol, NSUInteger i, BOOL * _Nonnull stop) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(i%numberOfColumn*(margin+subWidth) + margin, i/numberOfColumn*(margin+subHeight) + margin, subWidth, subHeight);
        button.backgroundColor = UIColor.whiteColor;
        [button setTitle:symbol forState:UIControlStateNormal];
        [button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        button.layer.cornerRadius = 4;
        [button addTarget:self action:@selector(charaterButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        [self.symbolPadView addSubview:button];
    }];
    
    
//    symbolString = @"( ) [ ] { } < >";
//    sysmbolArray = [symbolString componentsSeparatedByString:@" "];
//    [sysmbolArray enumerateObjectsUsingBlock:^(NSString * _Nonnull symbol, NSUInteger i, BOOL * _Nonnull stop) {
//        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//        button.frame = CGRectMake(i%numberOfColumn*(margin+subWidth) + margin + subWidth/2.0, 2*(margin+subHeight) + margin, subWidth, subHeight);
//        button.backgroundColor = UIColor.whiteColor;
//        [button setTitle:symbol forState:UIControlStateNormal];
//        [button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
//        button.layer.cornerRadius = 4;
//        [button addTarget:self action:@selector(charaterButtonTap:) forControlEvents:UIControlEventTouchUpInside];
//        [self.symbolPadView addSubview:button];
//    }];
    
    
    symbolString = @": ; \" '";
    sysmbolArray = [symbolString componentsSeparatedByString:@" "];
    [sysmbolArray enumerateObjectsUsingBlock:^(NSString * _Nonnull symbol, NSUInteger i, BOOL * _Nonnull stop) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake((i%numberOfColumn+2)*(margin+subWidth) + margin , 3*(margin+subHeight) + margin, subWidth, subHeight);
//        button.frame = CGRectMake((i%numberOfColumn+3)*(margin+subWidth) + margin , 3*(margin+subHeight) + margin, subWidth, subHeight);
        button.backgroundColor = UIColor.whiteColor;
        [button setTitle:symbol forState:UIControlStateNormal];
        [button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        button.layer.cornerRadius = 4;
        [button addTarget:self action:@selector(charaterButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        [self.symbolPadView addSubview:button];
    }];
    
    
    CGFloat buttonWidth = subWidth*1.9;
    // delete
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    CGFloat buttonX = numberOfColumn*(margin+subWidth) - buttonWidth;
    button.frame = CGRectMake(buttonX, 2*(margin+subHeight) + margin, buttonWidth, subHeight);
    button.backgroundColor = UIColor.whiteColor;
    [button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
    [button setImage:SEGAutoPicName(@"safeKeyboard_delete") forState:UIControlStateNormal];
    button.layer.cornerRadius = 4;
    [button addTarget:self action:@selector(deleteButtonTap) forControlEvents:UIControlEventTouchUpInside];
    UILongPressGestureRecognizer *press = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(reduceText:)];
    [button addGestureRecognizer:press];
    [self.symbolPadView addSubview:button];
    
    
    buttonWidth = subWidth*2+margin;
    // switch to number
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(margin, 3*(margin+subHeight) + margin, buttonWidth, subHeight);
        button.backgroundColor = UIColor.whiteColor;
        [button setTitle:@"123" forState:UIControlStateNormal];
        [button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        button.layer.cornerRadius = 4;
        [button addTarget:self action:@selector(switchToNumberPadButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        [self.symbolPadView addSubview:button];
    }
    
    
    // switch to letter
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//        button.frame = CGRectMake(10*(margin+subWidth) - buttonWidth, 3*(margin+subHeight) + margin, buttonWidth, subHeight);
        button.frame = CGRectMake(10*(margin+subWidth) - buttonWidth*2 - margin, 3*(margin+subHeight) + margin, buttonWidth, subHeight);
        button.backgroundColor = UIColor.whiteColor;
        [button setTitle:@"ABC" forState:UIControlStateNormal];
        [button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        button.layer.cornerRadius = 4;
        [button addTarget:self action:@selector(switchToLetterPadButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        [self.symbolPadView addSubview:button];
    }
    
    // done
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(10*(margin+subWidth) - buttonWidth, 3*(margin+subHeight) + margin, buttonWidth, subHeight);
        button.backgroundColor = UIColor.whiteColor;
        [button setTitle:@"完成" forState:UIControlStateNormal];
        [button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        button.layer.cornerRadius = 4;
        [button addTarget:self action:@selector(doneButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        [self.symbolPadView addSubview:button];
    }
}

- (void)setupLetterPad {
    self.letterPadView = [[UIView alloc] initWithFrame:CGRectMake(0, SEGSakeKeyBoardBannerHeight, SEGSakeKeyBoardWidth, SEGSakeKeyBoardPadHeight)];
    self.letterPadView.backgroundColor = UIColor.lightGrayColor;
    [self addSubview:self.letterPadView];
    self.letterButtonArray = [NSMutableArray array];
    
    CGFloat margin = 8;
    NSInteger numberOfRow = 4;
    NSInteger numberOfColumn = 10;
    CGFloat subHeight = floor((SEGSakeKeyBoardPadHeight - margin*(numberOfRow+1))*1.0/numberOfRow);
    CGFloat subWidth = floor((SEGSakeKeyBoardWidth - margin*(numberOfColumn+1))*1.0/numberOfColumn);
    CGFloat switchButtonWidth = 2 * subWidth;
    
    NSString *letterString = @"q w e r t y u i o p";
    NSArray *letterArray = [letterString componentsSeparatedByString:@" "];
    [letterArray enumerateObjectsUsingBlock:^(NSString * _Nonnull symbol, NSUInteger i, BOOL * _Nonnull stop) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(i%numberOfColumn*(margin+subWidth) + margin, i/numberOfColumn*(margin+subHeight) + margin, subWidth, subHeight);
        button.backgroundColor = UIColor.whiteColor;
        [button setTitle:symbol forState:UIControlStateNormal];
        [button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        button.layer.cornerRadius = 4;
        [button addTarget:self action:@selector(charaterButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        [self.letterPadView addSubview:button];
        [self.letterButtonArray addObject:button];
    }];
    
    letterString = @"a s d f g h j k l";
    letterArray = [letterString componentsSeparatedByString:@" "];
    [letterArray enumerateObjectsUsingBlock:^(NSString * _Nonnull symbol, NSUInteger i, BOOL * _Nonnull stop) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(i%numberOfColumn*(margin+subWidth) + margin + subWidth/2.0, (i/numberOfColumn+1)*(margin+subHeight) + margin, subWidth, subHeight);
        button.backgroundColor = UIColor.whiteColor;
        [button setTitle:symbol forState:UIControlStateNormal];
        [button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        button.layer.cornerRadius = 4;
        [button addTarget:self action:@selector(charaterButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        [self.letterPadView addSubview:button];
        [self.letterButtonArray addObject:button];
    }];
    
    letterString = @"z x c v b n m";
    letterArray = [letterString componentsSeparatedByString:@" "];
    [letterArray enumerateObjectsUsingBlock:^(NSString * _Nonnull symbol, NSUInteger i, BOOL * _Nonnull stop) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake((i%numberOfColumn + 1)*(margin+subWidth) + margin + subWidth/2.0, (i/numberOfColumn+2)*(margin+subHeight) + margin, subWidth, subHeight);
        button.backgroundColor = UIColor.whiteColor;
        [button setTitle:symbol forState:UIControlStateNormal];
        [button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        button.layer.cornerRadius = 4;
        [button addTarget:self action:@selector(charaterButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        [self.letterPadView addSubview:button];
        [self.letterButtonArray addObject:button];
    }];
    
    
    
    letterString = @", . : ;";
    CGFloat leftMargin = (SEGSakeKeyBoardWidth - (3*switchButtonWidth + 4*subWidth + 6*margin)) / 3.0;
    letterArray = [letterString componentsSeparatedByString:@" "];
    [letterArray enumerateObjectsUsingBlock:^(NSString * _Nonnull symbol, NSUInteger i, BOOL * _Nonnull stop) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(i%numberOfColumn*(margin+subWidth) + margin + switchButtonWidth + leftMargin, 3*(margin+subHeight) + margin, subWidth, subHeight);
        button.backgroundColor = UIColor.whiteColor;
        [button setTitle:symbol forState:UIControlStateNormal];
        [button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        button.layer.cornerRadius = 4;
        [button addTarget:self action:@selector(charaterButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        [self.letterPadView addSubview:button];
    }];
    
    // shift
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(margin, 2*(margin+subHeight) + margin, subWidth*1.5, subHeight);
        button.backgroundColor = UIColor.whiteColor;
        [button setImage:SEGAutoPicName(@"safeKeyboard_shift") forState:UIControlStateNormal];
        [button setImage:SEGAutoPicName(@"safeKeyboard_shift_fill") forState:UIControlStateSelected];
        [button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        button.layer.cornerRadius = 4;
        [button addTarget:self action:@selector(capitalButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        [self.letterPadView addSubview:button];
    }
    
    // delete
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(SEGSakeKeyBoardWidth - subWidth*1.5 - margin*2, 2*(margin+subHeight) + margin, subWidth*1.5, subHeight);
        button.backgroundColor = UIColor.whiteColor;
        [button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        button.layer.cornerRadius = 4;
        [button setImage:SEGAutoPicName(@"safeKeyboard_delete") forState:UIControlStateNormal];
        [button addTarget:self action:@selector(deleteButtonTap) forControlEvents:UIControlEventTouchUpInside];
        UILongPressGestureRecognizer *press = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(reduceText:)];
        [button addGestureRecognizer:press];
        [self.letterPadView addSubview:button];
    }
    
    // switch to number
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(margin, 3*(margin+subHeight) + margin, switchButtonWidth, subHeight);
        button.backgroundColor = UIColor.whiteColor;
        [button setTitle:@"123" forState:UIControlStateNormal];
        [button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        button.layer.cornerRadius = 4;
        [button addTarget:self action:@selector(switchToNumberPadButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        [self.letterPadView addSubview:button];
    }
    
    // switch to symbol
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(SEGSakeKeyBoardWidth - switchButtonWidth*2 - margin*3, 3*(margin+subHeight) + margin, switchButtonWidth, subHeight);
        button.backgroundColor = UIColor.whiteColor;
        [button setTitle:@"#+=" forState:UIControlStateNormal];
        [button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        button.layer.cornerRadius = 4;
        [button addTarget:self action:@selector(switchToSymbolPadButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        [self.letterPadView addSubview:button];
    }
    
    
    // done
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(SEGSakeKeyBoardWidth - switchButtonWidth - margin*2, 3*(margin+subHeight) + margin, switchButtonWidth, subHeight);
        button.backgroundColor = UIColor.whiteColor;
        [button setTitle:@"完成" forState:UIControlStateNormal];
        [button setTitleColor:UIColor.blackColor forState:UIControlStateNormal];
        button.layer.cornerRadius = 4;
        [button addTarget:self action:@selector(doneButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        [self.letterPadView addSubview:button];
    }
    
//    // space
//    {
//        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//        button.frame = CGRectMake(subWidth*2.5 + margin*4, 3*(margin+subHeight) + margin, SEGSakeKeyBoardWidth - (subWidth*2.5+margin*2)*2 - margin*5, subHeight);
//        button.backgroundColor = UIColor.whiteColor;
//        button.layer.cornerRadius = 4;
//        [button addTarget:self action:@selector(spaceButtonTap:) forControlEvents:UIControlEventTouchUpInside];
//        [self.letterPadView addSubview:button];
//    }
}


#pragma mark - Action

- (void)charaterButtonTap:(UIButton *)sender {
    if (@available(iOS 10.0, *)) {
        UIImpactFeedbackGenerator *impactLight = [[UIImpactFeedbackGenerator alloc]initWithStyle:UIImpactFeedbackStyleLight];
        [impactLight impactOccurred];
    }
    AudioServicesPlaySystemSound(1104);
    if (self.keyboardClickBlock) {
        self.keyboardClickBlock(SEGKeyBoardTypeInput, sender.titleLabel.text);
    }
}

- (void)deleteButtonTap {
    if (@available(iOS 10.0, *)) {
        UIImpactFeedbackGenerator *impactLight = [[UIImpactFeedbackGenerator alloc]initWithStyle:UIImpactFeedbackStyleLight];
        [impactLight impactOccurred];
    }
    AudioServicesPlaySystemSound(1104);
    if (self.keyboardClickBlock) {
        self.keyboardClickBlock(SEGKeyBoardTypeDelete, @"");
    }
}

- (void)reduceText:(UILongPressGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateBegan) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(deleteButtonTap) userInfo:nil repeats:YES];
    }else if (gesture.state == UIGestureRecognizerStateEnded || gesture.state == UIGestureRecognizerStateCancelled){
        [_timer invalidate];
        _timer = nil;
    }
}

- (void)spaceButtonTap:(UIButton *)sender {
    if (self.keyboardClickBlock) {
        self.keyboardClickBlock(SEGKeyBoardTypeInput, @" ");
    }
}

- (void)capitalButtonTap:(UIButton *)sender {
    sender.selected = !sender.selected;
    
    [self.letterButtonArray enumerateObjectsUsingBlock:^(UIButton *button, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *buttonTitle = button.titleLabel.text;
        if (sender.selected) {
            buttonTitle = [buttonTitle capitalizedString];
        } else {
            buttonTitle = [buttonTitle lowercaseString];
        }
        [button setTitle:buttonTitle forState:UIControlStateNormal];
    }];
}

- (void)switchToNumberPadButtonTap:(UIButton *)sender {
    [self bringSubviewToFront:self.numberPadView];
}

- (void)switchToSymbolPadButtonTap:(UIButton *)sender {
    [self bringSubviewToFront:self.symbolPadView];
}

- (void)switchToLetterPadButtonTap:(UIButton *)sender {
    [self bringSubviewToFront:self.letterPadView];
}

- (void)doneButtonTap:(UIButton *)sender {
    if (self.keyboardDoneBlock) {
        self.keyboardDoneBlock();
    }
}


@end
